import fs from 'fs'
import path from 'path'

import axios from 'axios'
import dayjs from 'dayjs'
import * as cheerio from 'cheerio'
import sharp from 'sharp'

import { getExtName, getBaseName, getHtml, getRecodeHtml, downloadImg, getHtmlByBrower } from '@/utils'

async function handler() {

  console.log('Hello template-crawler !')

  // ============================================================== 获取html ==============================================================
  getHtml('https://www.bilibili.com/').then(content => {
    // console.log(content)
    fs.writeFileSync('./html/bilibili-homepage.html', content)
  })

  // ============================================================== 使用无头浏览器 获取html ==============================================================
  getHtmlByBrower('https://www.bilibili.com/').then(content => {
    fs.writeFileSync('./html/bilibili-homepage.html', content)
  })

  // ============================================================== 解析html ==============================================================
  const str = await getHtml('https://www.bilibili.com/')
  const $ = cheerio.load(str)
  const title = $('title').html()
  let description = ''
  $('meta[name=description]').each(function (index) {
    description = $(this).prop('content')
  })
  console.log('\n')
  console.log({ title, description })
  console.log('\n')

  // ============================================================== html转码 ==============================================================
  let recodeHtml = await getRecodeHtml('http://www.fireemblem.net/fe/fe7', 'gb2312', 'utf8')
  fs.writeFileSync('./html/recodeHtml.html', recodeHtml)

  // ============================================================== 下载图片 ==============================================================
  let imgHtmlStr = await getHtml('https://feheroes.fandom.com/wiki/Eliwood:_Blazing_Knight')
  const $$ = cheerio.load(imgHtmlStr)
  let imgList: string[] = []
  $$('.fehwiki-tabber a.image').each(function (index) {
    let imageUrl = $(this).prop('href')
    if (imageUrl) {
      imgList.push(imageUrl)
    }
  })
  for (let eachImgUrl of imgList) {

    const fileName = /.*\/(?<name>.*\.webp)/.exec(eachImgUrl)?.groups?.name || ''
    const fileSavePath = path.resolve(__dirname, './imgs', fileName)

    await downloadImg(eachImgUrl, fileSavePath)

  }

  // ============================================================== 图片压缩 ==============================================================
  const sourcePath = path.resolve(__dirname, './imgs', 'Eliwood_Blazing_Knight_Face.webp')
  const outPath = path.resolve(__dirname, './imgs', 'min.Eliwood_Blazing_Knight_Face.webp')
  if (fs.existsSync(sourcePath)) {
    sharp(sourcePath).resize(800).toBuffer().then(data => {
      fs.writeFileSync(outPath, data)
    }).catch(err => console.log(err))
  }

}

handler()